package com.lw.leetcode.binary.c;

/**
 * Created with IntelliJ IDEA.
 * 1671. 得到山形数组的最少删除次数
 *
 * @author liw
 * @version 1.0
 * @date 2022/12/30 14:35
 */
public class MinimumMountainRemovals {

    public static void main(String[] args) {
        MinimumMountainRemovals test = new MinimumMountainRemovals();

        // 0
//        int[] nums = {1, 3, 1};

        // 3
//        int[] nums = {2, 1, 1, 5, 6, 2, 3, 1};

        // 2
        int[] nums = {9, 8, 1, 7, 6, 5, 4, 3, 2, 1};

        //
//        int[] nums = Utils.getArr(1000, 1, 100);
//        int[] nums1 = Utils.getArr(500, 1, 10000000, true, null);
//        int[] nums2 = Utils.getArr(500, 1, 10000000, true, null);
//        int[] nums = new int[1000];
//
//        for (int i = 0; i < 500; i++) {
//            nums[i] = nums1[i];
//            nums[999 - i] = nums2[i];
//        }
//        System.out.println(Arrays.toString(nums));


        int i = test.minimumMountainRemovals(nums);
        System.out.println(i);
    }

    public int minimumMountainRemovals(int[] nums) {
        int[] arr1 = find(nums);
        int length = nums.length;
        int l = length >> 1;
        for (int i = 0; i < l; i++) {
            int t = nums[i];
            nums[i] = nums[length - 1 - i];
            nums[length - 1 - i] = t;
        }
        int[] arr2 = find(nums);
        int max = 0;
        for (int i = 0; i < length; i++) {
            if (arr1[i] == 0 ||  arr2[length - 1 - i] == 0) {
                continue;
            }
            max = Math.max(max, arr1[i] + arr2[length - 1 - i] + 1);
        }
        return length - max;
    }

    private int[] find(int[] nums) {
        int length = nums.length;
        int[] arr = new int[length];
        int[] items = new int[length];
        int index = 0;
        items[0] = nums[0];
        for (int i = 1; i < length; i++) {
            int num = nums[i];
            if (items[index] < num) {
                items[++index] = num;
                arr[i] = index;
            } else if (items[index] == num) {
                arr[i] = index;
            } else {
                int v = find(items, index, num);
                if (v == 0 || items[v - 1] != num) {
                    items[v] = num;
                    arr[i] = v;
                } else {
                    arr[i] = v - 1;
                }
            }
        }
        return arr;
    }

    private int find(int[] items, int end, int t) {
        int st = 0;
        while (st < end) {
            int m = st + ((end - st) >> 1);
            if (items[m] > t) {
                end = m;
            } else {
                st = m + 1;
            }
        }
        return st;
    }

}
